package sc.server.world;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import sc.server.Database;

/**
 * Tile
 * 
 * @author Stephen Carmody
 */
public class Tile extends Container
{
    // Tile object identity in data interchange
    private static final int OBJECTTYPEID = 2;

    public static int MAPSIZE = 1000;
    public static int WIDTH = 200;
    public static int HALFMAPSIZE = (int) (Tile.MAPSIZE * 0.5);
    public static int HALFWIDTH = (int) (Tile.WIDTH * 0.5);

    // Grid of Tiles that make up the world
    private static Tile[][] tiles = new Tile[MAPSIZE][MAPSIZE];

    /**
     * Creates an instance of Tile.
     * 
     * @throws SQLException
     */
    private Tile(int id) throws SQLException
    {
        super(id);
    }

    /**
     * Returns tiles x grid position
     * 
     * @return x grid position
     */
    public int getTileX()
    {
        return this.getX() / Tile.WIDTH + Tile.HALFMAPSIZE;
    }

    /**
     * Returns tiles z grid position
     * 
     * @return z grid position
     */
    public int getTileZ()
    {
        return this.getZ() / Tile.WIDTH + Tile.HALFMAPSIZE;
    }

    @Override
    public int getObjectTypeID()
    {
        return Tile.OBJECTTYPEID;
    }

    /**
     * Reads all known Tiles from the database.
     * 
     * @throws SQLException
     */
    public static void initialise() throws SQLException
    {
        PreparedStatement readStmt = Database.getInstance().getConnection()
                .prepareStatement("select * from container where type=?");
        readStmt.setInt(1, Tile.OBJECTTYPEID);
        ResultSet rs = readStmt.executeQuery();
        Tile tile;
        int x, y, z;

        while (rs.next())
        {
            x = rs.getInt(4);
            y = rs.getInt(5);
            z = rs.getInt(6);
            tile = new Tile(rs.getInt(1));
            tile.setParent(rs.getInt(3));
            tile.setX(x);
            tile.setY(y);
            tile.setZ(z);
            tiles[(x/WIDTH)+HALFMAPSIZE][(z/WIDTH)+HALFMAPSIZE] = tile;
        }
    }
    
    /**
     * Creates a new Tile entry in the database.
     * 
     * @param d
     *            Database instance
     * @return New instance of Tile
     * @throws SQLException
     */
    public static Tile create(Database d) throws SQLException
    {
        return new Tile(Container.create(Tile.OBJECTTYPEID));
    }
    
    /**
     * Gets the tile at the specified position.
     * 
     * @param x
     * @param z
     * 
     * @return a Tile instance
     * @throws SQLException 
     * @throws SQLException 
     */
    public static Tile get(int gridx, int gridz) throws SQLException
    {
        if (tiles[gridx][gridz] == null)
            tiles[gridx][gridz] = new Tile(Container.create(Tile.OBJECTTYPEID));
        return tiles[gridx][gridz];
    }
}
